package com.telit.uav.service.impl;

import com.telit.android.feign.RemoteAndroidService;
import com.telit.common.entity.AppTask;
import com.telit.common.entity.CommEventTaskTrack;
import com.telit.common.util.RedisUtils;
import com.telit.uav.dao.AppCruiseTrackDao;
import com.telit.uav.dao.CommUavDao;
import com.telit.uav.entity.AppCruiseTrack;
import com.telit.uav.service.AppCruiseTrackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

;


/**
 * @Auther amy
 * @Describe
 */
@Service
public class AppCruiseTrackServiceImpl implements AppCruiseTrackService {

    @Autowired
    private AppCruiseTrackDao appCruiseTrackDao;

    @Autowired
    private CommUavDao commUavDao;

    @Autowired
    private RemoteAndroidService androidFeignClient;

    @Override
    public int uploadCruiseTrack(AppCruiseTrack appCruiseTrack) {
        // 判断巡航记录是否重复提交(同一个飞手同一个时间段,对于同一个类型的巡航类型只能有一个)
        if (!CollectionUtils.isEmpty(appCruiseTrackDao.listByConditionNoPage(appCruiseTrack))) {
            return 1;
        }
        String status = "3";
        Long taskId = appCruiseTrack.getTaskId();
        Long forestkeeperId = appCruiseTrack.getProtectorId();

        // 上传轨迹的时候,set轨迹id到子任务表中，并修改子任务状态
        androidFeignClient.updateCommEventTaskTrackByParam(
                new CommEventTaskTrack().setTrackId(appCruiseTrack.getId()).setStatus(status).setTaskId(
                        appCruiseTrack.getTaskId()).setForestkeeperId(appCruiseTrack.getProtectorId()));

        //巡航类型为“日常巡航”，任务的结束时间、完成时间为巡护的完成时间
        if ("7".equals(appCruiseTrack.getPatrolType())) {
            // 修改主任务状态
            androidFeignClient.updateAppTaskByParam(
                    new AppTask().setStatus(status).setFinishTime(appCruiseTrack.getEndTime()).setEndTime(
                            appCruiseTrack.getEndTime()).setId(appCruiseTrack.getTaskId()));
        } else {
            //非日常巡航任务修改主任务表状态
            List<Long> commEventTaskTrackIdList = (List<Long>) androidFeignClient.selectIdByTaskIdAndStatus(taskId,
                    status, forestkeeperId).getData();
            if (CollectionUtils.isEmpty(commEventTaskTrackIdList)) {
                androidFeignClient.updateAppTaskByParam(
                        new AppTask().setStatus(status).setFinishTime(appCruiseTrack.getEndTime()).setId(
                                appCruiseTrack.getTaskId()));
            }
        }
        int flag = appCruiseTrackDao.insert(appCruiseTrack);

        //清空redis缓存
        RedisUtils.removeBoundHash(String.valueOf(appCruiseTrack.getTaskId()),
                String.valueOf(appCruiseTrack.getProtectorId()));
        return flag;

    }

}
